import com.sun.net.httpserver.HttpExchange;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.Mockito.*;

/**
 * HTTP测试工具类
 */
public class HttpTestUtils {

    /**
     * 创建模拟的HttpExchange
     */
    public static HttpExchange createMockExchange(String path, String query, String requestBody)
            throws URISyntaxException {
        HttpExchange exchange = mock(HttpExchange.class);

        // 模拟URI
        URI uri = new URI("http://localhost:8001" + path + (query != null ? "?" + query : ""));
        when(exchange.getRequestURI()).thenReturn(uri);

        // 模拟请求体
        InputStream inputStream = new ByteArrayInputStream(requestBody.getBytes());
        when(exchange.getRequestBody()).thenReturn(inputStream);

        // 模拟响应体
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        when(exchange.getResponseBody()).thenReturn(outputStream);

        return exchange;
    }

    /**
     * 创建模拟的HttpExchange（简化版）
     */
    public static HttpExchange createMockExchange(String path) throws URISyntaxException {
        return createMockExchange(path, null, "");
    }

    /**
     * 创建模拟的HttpExchange（带查询参数）
     */
    public static HttpExchange createMockExchange(String path, String query) throws URISyntaxException {
        return createMockExchange(path, query, "");
    }

    /**
     * 从模拟的HttpExchange获取响应内容
     */
    public static String getResponseContent(HttpExchange exchange) {
        OutputStream outputStream = exchange.getResponseBody();
        if (outputStream instanceof ByteArrayOutputStream) {
            return ((ByteArrayOutputStream) outputStream).toString();
        }
        return "";
    }

    /**
     * 创建路径参数Map
     */
    public static Map<String, String> createPathParams(String... keyValuePairs) {
        Map<String, String> params = new HashMap<>();
        for (int i = 0; i < keyValuePairs.length; i += 2) {
            if (i + 1 < keyValuePairs.length) {
                params.put(keyValuePairs[i], keyValuePairs[i + 1]);
            }
        }
        return params;
    }
}